<?php
/**
 * (ajax) 海外仓发货需求
 */

namespace App\Admin\Ajax\CustomerDelivery;


use App\Logic\Plat\Rakuten\Overseas\GuCang\Order\OverseasOrder;
use App\Models\Basics\ExpressCompany;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerDeliveryLogistics;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Models\OverSeasBa\DropshippingInventoryFnsku;
use App\Models\Rakuten\RakutenOrder;
use App\Models\Sys\Logs;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class DeliveryAbroadAjax{


    /**
     * 编辑
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listEdit($id){
        $delivery = CustomerDelivery::query()->find($id);
        return view('customer-delivery.delivery-abroad.modal-edit',compact('id','delivery'));
    }

    public function doListEdit($param){
        try{
            DB::beginTransaction();

            $deliveryObj = CustomerDelivery::query()->find($param['id']);
            if($deliveryObj->status == CustomerDelivery::STATUS_DELIVERY_YES) throw new \Exception('发货单状态有误!');

            $orderObj = CustomerOrder::query()->where('order_no', $deliveryObj->order_no)->first();
            if(empty($orderObj)) throw new \Exception('订单异常!');

            $receiverFields = ['country','receiver','address','state','city','postcode','phone','cpf'];
            foreach($param as $k => $v){
                if(in_array($k, $receiverFields)){

                    $deliveryObj->receiver->{$k} = $v;

                    if ($k == 'cpf')  break; //订单表中没有cpf字段,所以参数存在该字段则跳过，cpf字段不更新
                    $orderObj->receiver->{$k} = $v;
                }
            }

            //更新地址
            if(!$deliveryObj->receiver->save()) throw new \Exception('编辑地址失败!');

            //更新订单
            if(!$orderObj->receiver->save()) throw new \Exception('编辑订单失败!');

            //添加日志
            Logs::logs('customer-order-abroad', "海外发货单：{$deliveryObj->delivery_no} 编辑收货人信息", $deliveryObj->id);
            DB::commit();
            return response()->json(['status' =>true, 'message' => '编辑成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 发货
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ship($id){
        $delivery = CustomerDelivery::query()->findOrFail($id);
        return view('customer-delivery.delivery-abroad.modal-ship',compact('id','delivery'));
    }

    /**
     * 发货
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function doShip($id){

        $deliveryObj = CustomerDelivery::query()->findOrFail($id);
        if(!$deliveryObj || $deliveryObj->status != CustomerDelivery::STATUS_DELIVERY_NO){
            return response()->json(['status' => false, 'message' => '发货单有误!']);
        }
        try{
            DB::beginTransaction();

            //更新发货单
            $deliveryObj->status = CustomerDelivery::STATUS_DELIVERY_YES; //发货状态 (5:已发货)
            $deliveryObj->delivered_at = date('Y-m-d H:i:s');
            if(!$deliveryObj->save()) throw new \Exception('操作失败2!');

            //更新发货明细
            $deliveryDetailObj = CustomerDeliveryDetail::query()
                ->where('delivery_no', $deliveryObj->delivery_no)
                ->where('status', CustomerDeliveryDetail::STATUS_DELIVERY_NO) //发货单状态 (3:待发货)
                ->where('delivery_type', CustomerDelivery::DELIVERY_TYPE_ABROAD) //发货方式 (2:海外仓)
                ->update([
                    'status' =>CustomerDeliveryDetail::STATUS_DELIVERY_YES, //发货明细状态 (5:已发货)
                    'delivered_at' => $deliveryObj->delivered_at ?? date('Y-m-d H:i:s') //发货时间
                ]);
            if(!$deliveryDetailObj) throw new \Exception('操作失败2-1!');

            //日志
            Logs::logs('customer-order-abroad', "海外发货单：{$deliveryObj->delivery_no} 已发货", $id);

            /*//erp客户订单同步至谷仓海外仓(谷仓)
            $rakutenOrder = RakutenOrder::query()->where('order_id', $deliveryObj->order_no)->first();
            if ($rakutenOrder) {
                $dropshippingInventoryFlag = DropshippingInventoryFnsku::_checkDropshippingInventoryFnsku($rakutenOrder);
                if ($dropshippingInventoryFlag == true) {
                    $overseasOrder = OverseasOrder::getReferenceOrder($deliveryObj->order_no);
                    if ($overseasOrder){
                        CustomerDeliveryDetail::query()
                            ->where('delivery_no', $deliveryObj->delivery_no)
                            ->where('delivery_type', CustomerDelivery::DELIVERY_TYPE_ABROAD) //发货方式 (2:海外仓)
                            ->update([
                                'overseas_order_id' => $overseasOrder->order_code ?? ''
                            ]);
                    }else{
                        //海外仓(代发)库存满足时,创建海外仓(谷仓)订单
                        $flag = OverseasOrder::createOrder([$rakutenOrder]);
                        if ($flag == true) {
                            //更新erp客户订单
                            $customerOrder = CustomerOrder::query()->where('order_no', $deliveryObj->order_no)->first();
                            $customerOrder->sync_status = CustomerOrder::SYNC_YES;
                            if (!$customerOrder->save()) {
                                throw new \Exception('订单同步至海外仓失败2-1!');
                            }
                            //更新erp客户订单明细
                            CustomerOrderDetails::query()
                                ->where('order_no', $deliveryObj->order_no)
                                ->update([
                                    'sync_status' =>CustomerOrderDetails::SYNC_YES //1:已同步
                                ]);
                        }
                    }
                }
            }*/

            DB::commit();
            return response()->json(['status' => true,'message' => '发货成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 删除发货单
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delDelivery($id){
        try{
            DB::beginTransaction();

            $deliveryObj = CustomerDelivery::query()->find($id);
            if($deliveryObj->status != CustomerDelivery::STATUS_DELIVERY_NO) throw new \Exception('状态有误!');

            foreach ($deliveryObj->detail as $detail){
                //更新(回写)消费订单详情
                $orderDetailObj = CustomerOrderDetails::query()->find($detail->order_detail_id);
                if (empty($orderDetailObj)) break;
                $orderDetailObj->apply_num -= $detail->apply_num;
                $num = $orderDetailObj->apply_num;
                if($num == 0){
                    $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_NO;    //1:未申请
                }else{
                    if($orderDetailObj->order_num > $num){
                        $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_PART;    //2:部分申请
                    }else{
                        $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_YES;    //3:完全申请
                    }
                }
                if(!$orderDetailObj->save()){
                    break;
                }
            }
            if(!$deliveryObj->delete()) throw new \Exception('删除失败!');

            //日志
            Logs::logs('customer-order-abroad', "海外发货单：{$deliveryObj->delivery_no} 已删除", $id);
            DB::commit();
            return response()->json(['status' => true, 'message' => '删除成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    //更新物流
    public function listLogistics($id){
        $delivery = CustomerDelivery::query()->findOrFail($id);
        return view('customer-delivery.delivery-abroad.modal-logistics',compact('id','delivery'));
    }

    public function doLogistics($param){

        $deliveryObj = CustomerDelivery::query()->findOrFail($param['id']);
        if($deliveryObj->status != CustomerDelivery::STATUS_DELIVERY_YES){
            return response()->json(['status' => false, 'message' => '发货单状态有误!']);
        }

        //乐天（rakuten）
        if ($deliveryObj->plat_id == SysPlat::PLAT_RAKUTEN) {
            if(!$param['tracking_no'] || !$param['express_company_id'] || !$param['delivered_at']){
                return response()->json(['status' => false, 'message' => '请补全乐天物流信息（追踪号、物流公司、发货时间）!']);
            }
            $expressCompany = ExpressCompany::getModel($param['express_company_id']);
            if(!$expressCompany){
                return response()->json(['status' => false, 'message' => '物流公司不存在!']);
            }
            if (empty($expressCompany->name_en)) {
                return response()->json(['status' => false, 'message' => '物流公司异常：未配置名称(日文)!']);
            }
            //（补充乐天平台物流信息）
            $paramData['logistics_type'] = $expressCompany->name_en; //乐天物流公司（日文名称）
            $paramData['delivered_at'] = $param['delivered_at'] ?? date('Y-m-d H:i:s', time());  //发货时间
        }

        if (!isset($param['delivered_at'])){ //发货时间不存在，则默认发货时间
            $param['delivered_at'] = date('Y-m-d H:i:s', time());
        }
        $paramData['shipping_date'] = date('Y-m-d', strtotime($param['delivered_at']));
        $paramData['tracking_no'] = $param['tracking_no'];
        $paramData['total_weight'] = $param['total_weight'] ?? 0;
        $paramData['shipping_fee'] = $param['shipping_fee'] ?? 0;
        $paramData['other_fee']  = $param['other_fee'] ?? 0;
        if (intval($param['total_weight']) > 0 || intval($param['total_weight']) > 0 || intval($param['other_fee']) > 0) {
            $paramData['logistics_fee_status'] = CustomerDeliveryDetail::LOGISTICS_FEE_YES;  //物流费用，已更新 (0:未更新 1:已更新)
        }
        if ($param['tracking_no']) {
            $paramData['sync_status'] = CustomerDeliveryDetail::SYNC_STATUS_YES; //物流追踪号同步，已同步 (0:未同步 1:已同步)
        }

        DB::beginTransaction();
        try{
            //更新发货物流
            CustomerDeliveryLogistics::query()->updateOrCreate(
                ['delivery_no' => $deliveryObj->delivery_no],
                [
                    'order_no'    => $deliveryObj->order_no,
                    'express_company_id' => $param['express_company_id'] ?? null,
                    'area_id'            => $param['area_id'] ?? null,
                    'express_channel_id' => $param['express_channel_id'] ?? null,
                    'tracking_no'        => $param['tracking_no'] ?? null,
                    'total_weight'       => $param['total_weight'] ?? 0,
                    'shipping_fee'       => $param['shipping_fee'] ?? 0,
                    'other_fee'          => $param['other_fee'] ?? 0,
                    'delivered_at'       => $param['delivered_at'] ?? null,
                    'arrived_at'         => $param['arrived_at'] ?? null,
                ]
            );

            //更新发货明细
            $deliveryDetailObj = CustomerDeliveryDetail::query()
                ->where('delivery_no', $deliveryObj->delivery_no)
                ->update($paramData);
            if(!$deliveryDetailObj){
                return response()->json(['status' => false, 'message' => '发货明细,更新失败!']);
            }

            //更新发货
            $deliveryObj->logistics_status = CustomerDelivery::LOGISTICS_STATUS_YES; //物流状态 (2:已更新)
            if(!$deliveryObj->save()) throw new \Exception('更新失败!');

            Logs::logs('customer-order-abroad', "发货单：{$deliveryObj->delivery_no} 物流信息已更新", $deliveryObj->id);
            DB::commit();
            return response()->json(['status' =>true, 'message' => '物流更新成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }


    /**
     * 同步物流状态
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function syncOutbound($param){
        try{

            if(empty($param['accountId'])) return response()->json(['status' => false, 'message' => '发货账号不能为空!']);
            if(empty($param['deliveryOrderNo'])) return response()->json(['status' => false, 'message' => '实际发货订单号异常!']);

            ////同步
            //Artisan::call('customer:outbound',
            //    ['account_id' => $param['accountId'], 'delivery_order_no' => $param['deliveryOrderNo']]);

            return response()->json(['status' => true, 'message' => '同步成功!']);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误!']);
        }
    }

}
